import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User } from '../types'
import { authApi } from '../api'
import { tokenUtils, userUtils } from '../utils'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(userUtils.getUser())
  const token = ref<string | null>(tokenUtils.getToken())
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  const login = async (username: string, password: string, remember = false) => {
    try {
      const response = await authApi.login({ username, password, remember })
      
      if (response.code === 200) {
        const { token: newToken, user: userInfo } = response.data
        
        // 保存token和用户信息
        token.value = newToken
        user.value = userInfo
        tokenUtils.setToken(newToken)
        userUtils.setUser(userInfo)
        
        return { success: true, message: response.message }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('Login error:', error)
      return { success: false, message: '登录失败，请重试' }
    }
  }

  // 登出
  const logout = async () => {
    try {
      await authApi.logout()
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      // 清除本地状态
      token.value = null
      user.value = null
      tokenUtils.removeToken()
      userUtils.removeUser()
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await authApi.getUserInfo()
      if (response.code === 200) {
        user.value = response.data
        userUtils.setUser(response.data)
        return response.data
      }
    } catch (error) {
      console.error('Fetch user info error:', error)
      // 如果获取用户信息失败，可能token已过期，清除登录状态
      await logout()
    }
  }

  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string, confirmPassword: string) => {
    try {
      if (newPassword !== confirmPassword) {
        return { success: false, message: '两次输入的密码不一致' }
      }

      const response = await authApi.changePassword({
        oldPassword,
        newPassword,
        confirmPassword
      })

      return {
        success: response.code === 200,
        message: response.message
      }
    } catch (error) {
      console.error('Change password error:', error)
      return { success: false, message: '修改密码失败，请重试' }
    }
  }

  return {
    // 状态
    user,
    token,
    isLoggedIn,
    
    // 操作
    login,
    logout,
    fetchUserInfo,
    changePassword
  }
})